<?php
/**
 * Created by PhpStorm.
 * User: zhuyujun
 * Date: 2018/3/9
 * Time: 11:21
 */

$blackList = [
    '/nginx/',
    'nginx/getSideMenu',
    'nginx/nginxLogData',
    '_debugbar/',
    'nginx/getIpUserSelect',
    'favicon.ico',
    '/assets',
];


$dbHost='118.178.24.119';
$dbPort='2017';
$dbDatabase='eguantong';
$dbUseruame='baoxuan';
$dbPassword='bx123456';
//$connect = mysqli_connect($dbHost,$dbUseruame,$dbPassword,$dbDatabase,$dbPort);



$allowRecord = true;
foreach ($blackList as $filterStr){
    if(false !== strpos($_SERVER['REQUEST_URI'],$filterStr)){
        $allowRecord =  false;//黑名单的访问不进行统计
    }
}


if($allowRecord){
    $visitUrl = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $visitHost = $visitUrl;
    $visitIp = $_SERVER['REMOTE_ADDR'];
    $visitTime = $_SERVER['REQUEST_TIME'];
    $visitMethod = $_SERVER['REQUEST_METHOD'];


    if (strstr($visitUrl, 'http') !== false) {
        $visitUrl .= 'http://' . $visitUrl;
    }


    $visitGetParam = "";
    if(!empty($_GET)){
        foreach ( $_GET as $k => $v )
        {
            $visitGetParam.= "$k=" . urlencode( $v ). "&" ;
        }
        $visitGetParam = substr($visitGetParam,0,-1);
    }

    $visitPostParam = "";
    if(!empty($_POST)){
        foreach ( $_POST as $k => $v )
        {
            $visitPostParam.= "$k=" . urlencode( $v ). "&" ;
        }
        $visitPostParam = substr($visitPostParam,0,-1);
    }

    $headers = getallheaders();//header信息

    //数据入库
    $connect = mysqli_connect('192.168.1.202','root','root','laravel') or die('Unale to connect');
//    $connect = mysqli_connect($dbHost,$dbUseruame,$dbPassword,$dbDatabase,$dbPort);
    if($connect){
        $insertRow = [];

        $insertRow['visit_ip'] = $visitIp;
        $insertRow['visit_host'] = $visitHost;
        $insertRow['visit_time'] = $visitTime;
        $insertRow['visit_method'] = $visitMethod;
//        $insertRow['visit_uri'] = $visitUri;
        $insertRow['visit_get_param'] = $visitGetParam;
        $insertRow['visit_post_param'] = $visitPostParam;
//        $insertRow['visit_status_code'] = $httpCode;
        $insertRow['visit_header'] = json_encode($headers);

        insertDataBase($connect,'visit_log',$insertRow);
    }


}

function insertDataBase($connect,$tableName,$insertRow){
    $inserKey = '(';
    $insertValue = '(';
    foreach ($insertRow as $key => $value){
        $inserKey .= "`{$key}`,";
        if($key == 'content'){
            $insertValue .= "'".urlencode($value)."',";
        }else{
            $insertValue .= "'{$value}',";
        }

    }
    $inserKey = substr($inserKey,0,-1).")";
    $insertValue = substr($insertValue,0,-1).")";

    $sql = "INSERT INTO `{$tableName}`{$inserKey} VALUES {$insertValue}";
    $re = mysqli_query($connect,$sql);
}